﻿using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters
{
    /// <summary>
    /// 新增轮播图命令处理
    /// </summary>
    public class AddNewCarouselCommandHandlter : IRequestHandler<AddNewCarouselCommand, ApiResult<int>>
    {
        /// <summary>
        /// 轮播仓储
        /// </summary>
        private readonly IBaseRepository<CarouelChartModel> _carouselRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<AddNewCarouselCommandHandlter> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="carouselRepository">轮播仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public AddNewCarouselCommandHandlter(IBaseRepository<CarouelChartModel> carouselRepository, IMapper mapper, ILogger<AddNewCarouselCommandHandlter> logger)
        {
            _carouselRepository = carouselRepository;
            this.mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理新增轮播图命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddNewCarouselCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证标题是否已存在
                var carouselDtos = _carouselRepository.GetAll().Where(x => x.CarouelChartTitle == request.CarouelChartTitle);
                // 如果已存在，返回错误
                if(carouselDtos.Any())
                {

                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "轮播图标题已存在！！!",
                        data = 0
                    };
                }
                _logger.LogInformation("开始处理轮播图新增命令，标题：{Title}", request.CarouelChartTitle);
                
                // 创建轮播图实体
                var carouselEntity = mapper.Map<CarouelChartModel>(request);
                carouselEntity.CreatedTime = DateTime.Now;
                carouselEntity.UpdatedTime = DateTime.Now;
                carouselEntity.CreatedBy = 1;
                carouselEntity.UpdatedBy = 0;
                
                _logger.LogDebug("轮播图实体映射完成，实体信息：{@Entity}", carouselEntity);
 
                // 保存到数据库
                _logger.LogInformation("开始保存轮播图到数据库");
                var result = await _carouselRepository.AddAsync(carouselEntity);
                _logger.LogInformation("数据库保存完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    _logger.LogInformation("轮播图新增成功，ID：{Id}", carouselEntity.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = "轮播图新增成功",
                        data = carouselEntity.Id
                    };
                }
                else
                {
                    _logger.LogWarning("轮播图新增失败，数据库未返回影响行数");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "轮播图新增失败",
                        data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "轮播图新增过程中发生异常，标题：{Title}", request.CarouelChartTitle);
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"轮播图新增异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
}
